package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 该线程任务负责与指定客户端完成HTTP交互。
 * ClientHandler与客户端交流的流程分成三步
 * 1:解析请求
 * 2:处理请求
 * 3:发送相应
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run(){
        try {
            //1 解析请求
            HttpServletRequest request = new HttpServletRequest(socket);

            HttpServletResponse response = new HttpServletResponse(socket);
            //2 处理请求
            String path = request.getUri();//path: /myweb/index.html
            File root = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
            File staticDir = new File(root,"static");
            File file = new File(staticDir,path);
            System.out.println("页面是否存在: "+file.exists());

            //3 发送相应

            //3.1 发送消息行。
            //3.3 发送相应正文（index.html页面的数据）
            if (file.isFile()){
                response.setContentFile(file);
            }else {
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File(staticDir,"root/404.html");
                response.setContentFile(file);
            }

            response.response();

        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }finally {
            //HTTP协议要求，相应客户端后就要断开TCP链接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
